from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import ListAPIView, UpdateAPIView, CreateAPIView, ListCreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializer import AreaSerializer, AddressSerializer
from users.models import Address, User


class AreasView(CacheResponseMixin,ListAPIView):
    serializer_class = AreaSerializer
    queryset = Area.objects.filter(parent=None)

class AreaView(CacheResponseMixin,ListAPIView):
    serializer_class = AreaSerializer
    #queryset = Area.objects.filter(parent=self.kwargs["pk"])
    def get_queryset(self):
        #
        return Area.objects.filter(parent=self.kwargs["pk"])

class AddressesView(CreateAPIView,UpdateAPIView):
    """
         保存收货地址
         获取收货地址
         更新收货地址
     """
    serializer_class = AddressSerializer
    queryset = Address.objects.all()

    def get(self, request, *args, **kwargs):
        # 获取用户
        user = request.user
        # 查询地址
        address = Address.objects.filter(user=user, is_deleted=False)
        # 插叙默认地址
        default_address_id = user.default_address_id
        if default_address_id is None:
            default_address_id = 'False'
        # 序列化地址对象
        ser = self.get_serializer(address, many=True)

        addresses = ser.data

        return Response({'addresses': addresses, 'default_address_id': default_address_id})

    def delete(self,request,pk,*args,**kwargs):
        try:
            address = Address.objects.get(id=pk)
        except Exception as e:
            return Response({'error':"错误的id"},status=status.HTTP_400_BAD_REQUEST)
        address.is_deleted = True
        address.save()
        return Response()

class DefaultAddressesView(APIView):

    def put(self,request,pk):
        user = request.user
        try:
            address = Address.objects.get(id=pk)
        except:
            return Response({'error':"地址不存在"},status=status.HTTP_400_BAD_REQUEST)
        user.default_address_id = pk
        user.save()

        # return Response({"default_address_id": user.default_address_id})
        return Response({"default_address_id": 'OK'})




